// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async (event, context) => {
    const { inviteRole, formOption } = event.data
    const wxContext = cloud.getWXContext()
    const db = cloud.database()

    try {
        // 1. 检查当前用户是否已有两条配置记录
        const checkRes = await db.collection('form_settings')
            .where({
                _openid: wxContext.OPENID
            })
            .get()

        // 2. 查找是否已存在当前 inviteRole 的记录
        const existingRecord = checkRes.data.find(item => item.inviteRole === inviteRole)

        // 3. 存在则更新，不存在则新增
        if (existingRecord) {
            await db.collection('form_settings')
                .doc(existingRecord._id)
                .update({
                    data: {
                        formOption: formOption,
                        updatedAt: db.serverDate(),
                    }
                })
        } else {
            await db.collection('form_settings')
                .add({
                    data: {
                        _openid: wxContext.OPENID,
                        inviteRole: inviteRole,
                        formOption: formOption,
                        createdAt: db.serverDate(),
                        updatedAt: db.serverDate()
                    }
                })
        }

        // 4. 确保另一条记录存在（如果不存在则创建默认配置）
        const otherRole = inviteRole === 1 ? 2 : 1
        const otherRecord = checkRes.data.find(item => item.inviteRole === otherRole)

        if (!otherRecord) {
            const defaultConfig = getDefaultConfig(otherRole)
            await db.collection('form_settings')
                .add({
                    data: {
                        _openid: wxContext.OPENID,
                        inviteRole: otherRole,
                        formOption: defaultConfig,
                        createdAt: db.serverDate(),
                        updatedAt: db.serverDate()
                    }
                })
        }

        return {
            success: true,
            message: '配置保存成功'
        }
    } catch (err) {
        console.error('保存失败:', err)
        return {
            success: false,
            message: '配置保存失败',
            error: err
        }
    }
}

// 获取默认配置的函数
function getDefaultConfig(role) {
    if (role === 1) {
        return {
            applyTime: true,
            applyNickName: true,
            applyName: true,
            applyPhone: true,
            applyWx: true,
            applyMsg: true
        }
    } else if (role === 2) {
        return {
            userName: true,
            contact: true,
            phone: true,
            email: true,
            address: true,
            business: true,
            saleChannel: true,
            businessLicense: true,
            foodBusinessLicense: true,
            idCard: true
        }
    }
    return {}
}